import requests
from flask import Flask, request

app = Flask(__name__)

@app.route('/send', methods=['GET', 'POST'])
def send_message():
    # 获取参数
    corpid = request.values.get('corpid')
    corpsecret = request.values.get('corpsecret')
    agentid = request.values.get('agentid')
    title = request.values.get('title', '无标题')
    description = request.values.get('description', '无内容')
    url = request.values.get('url', 'URL')

    # 参数校验
    if not corpid or not corpsecret or not agentid:
        return "参数不全", 400

    # 获取 access_token
    token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}"
    token_resp = requests.get(token_url)
    token_json = token_resp.json()
    access_token = token_json.get('access_token')
    if not access_token:
        return "参数错误", 400

    # 构造消息体
    data = {
        "touser": "@all",
        "msgtype": "news",
        "agentid": agentid,
        "news": {
           "articles" : [
              {
                "title" : title,
		        "description": description.replace('\n', '<br>'),
		        "url": url,
                "picurl" : "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png"
              }
           ]
        }
    }

    # 发送消息
    send_url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
    resp = requests.post(send_url, json=data)
    return resp.text

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)